package models

import (
	"time"

	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
	"fmt"
)

type BookChapter struct {
	Id         int       `orm:"column(id);auto"`
	Status     int8      `orm:"column(status)" description:"状态"`
	BookId     int       `orm:"column(book_id)" description:"小说ID"`
	No         int       `orm:"column(no)" description:"章节NO"`
	Name       string    `orm:"column(name);size(50)" description:"章节名称"`
	Price      int       `orm:"column(price)" description:"单价"`
	CreateTime time.Time `orm:"column(create_time);type(datetime)" description:"入库时间"`
	UpdateTime time.Time `orm:"column(update_time);type(datetime);null" description:"更新时间"`
	SerialId   string    `orm:"column(serial_id);size(32)" description:"序列编号"`
	Words      int       `orm:"column(words)" description:"章节字数"`
}

func (t *BookChapter) TableName() string {
	return "book_chapter"
}

func init() {
	orm.RegisterModel(new(BookChapter))
}

//func GetChapterByBookId(bookId int) ([]*BookChapter,error){
//	o := orm.NewOrm()
//	bookChapters := make([]*BookChapter,0)
//	_,err := o.Raw("select * from book_chapter where book_id = ?",bookId).QueryRows(bookChapters)
//	if err != nil {
//		fmt.Println("select book_chapter err",err)
//		return nil,err
//	}
//	return bookChapters,nil
//}

func GetChapterList(page, pageSize int, cond *orm.Condition) ([]map[string]string, int64, map[int]map[string]string) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	list := make([]*BookChapter, 0)
	query := o.QueryTable(TableName("book_chapter"))
	query = query.SetCond(cond)
	total, _ := query.Count()
	query.OrderBy("no").Limit(pageSize, offset).All(&list)

	results := make([]map[string]string, 0)
	for _, v := range list {
		result := make(map[string]string)
		result["id"] = strconv.Itoa(v.Id)
		result["no"] = strconv.Itoa(v.No)
		result["name"] = v.Name
		result["words"] = strconv.Itoa(v.Words)
		result["price"] = strconv.Itoa(v.Price)
		result["SerialId"] = v.SerialId
		results = append(results, result)
	}
	tableHead := map[int]map[string]string{
		0: {"id": "章节Id"},
		1: {"no": "章节序号"},
		2: {"name": "章节名"},
		3: {"words": "字数"},
		4: {"price": "书币"},
	}
	return results, total, tableHead
}

func UpdatePriceById(ids string, price int, bookId int) (int64, error) {
	o := orm.NewOrm()
	idArr := strings.Split(ids, ",")
	var affectRow int64
	affectRow = 0
	for _, v := range idArr {
		id, _ := strconv.Atoi(v)
		bookChapter := &BookChapter{Id: id, Price: price}
		num, err := o.Update(bookChapter, "Price")
		if err != nil {
			return 0, err
			fmt.Println("update price error", err)
		}
		affectRow = affectRow + num
	}

	// 更新完书币后，重新计算小说的总价
	total := 0
	o.Raw("select sum(price) from book_chapter where book_id = ?", bookId).QueryRow(&total)
	_, err := o.Raw("update book set chapter_price_sum = ? where id = ?", total, bookId).Exec()
	if err != nil {
		return 0, err
	}
	return affectRow, nil
}
